package com.rain.shoppingscienceproj.ui.fragment.order;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;

import com.rain.shoppingscienceproj.R;
import com.rain.shoppingscienceproj.http.BaseSubscriber;
import com.rain.shoppingscienceproj.http.ExceptionHandle;
import com.rain.shoppingscienceproj.http.RetrofitClient;
import com.rain.shoppingscienceproj.module.OrderBetweenDto;
import com.rain.shoppingscienceproj.ui.activity.logistics.LogisticsActivity;
import com.rain.shoppingscienceproj.ui.adapter.OrderAdapter;
import com.rain.shoppingscienceproj.ui.base.GlobalData;
import com.rain.shoppingscienceproj.ui.fragment.BaseFragment;
import com.rain.shoppingscienceproj.ui.utile.DialogUtils;
import com.rain.shoppingscienceproj.utils.toast.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import okhttp3.ResponseBody;

/**
 * ========================================================
 * <p>
 * Author：admin
 * Time  ：2018-09-02 16:31
 * Desc  ：待收貨
 * <p>
 * ========================================================
 */
public class WaitGetFragment extends BaseFragment {
    public static final String BUNDLE_TITLE = "data";
    @BindView(R.id.rv_order_get)
    RecyclerView mRecyclerView;
    @BindView(R.id.order_refreshLayout)
    SmartRefreshLayout refreshLayout;
    private OrderAdapter makeOrderAdapter;
    private boolean isViewShow = false;
    @BindView(R.id.ll_wait_get_data)
    LinearLayout ll_wait_get_data;
    private int page = 1;
    private List<OrderBetweenDto> list = new ArrayList<>();
    public static Fragment newInstance(String typeData) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(BUNDLE_TITLE, typeData);
        WaitGetFragment fragment = new WaitGetFragment();
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public int getLayoutResId() {
        return R.layout.fragment_order_wait_get;
    }

    @Override
    public void finishCreateView(Bundle bundle) {
        isViewShow = true;
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        makeOrderAdapter = new OrderAdapter(getActivity(), 1);
        mRecyclerView.setAdapter(makeOrderAdapter);
        userInfo = GlobalData.getUserInfo();
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadmore(false);
//        init();
        initListener();
    }

    @Override
    public void onStart() {
        super.onStart();
//        init(2);
    }

    @Override
    protected void lazyLoad() {
        super.lazyLoad();
        if (isViewShow)
            refresh();
    }

    private void init(int i) {
        Map<String, String> map = new HashMap<>();
        map.put("userId", userInfo.getUserId());
        map.put("token", userInfo.getToken());
//        map.put("shopId", userInfo.getShopId());
        map.put("page",  page + "");
        map.put("status", "2");
        loadingDialog.show();
        RetrofitClient.getInstance(getActivity())
                .createBaseApi()
                .orderStatus(map, new BaseSubscriber<List<OrderBetweenDto>>(getActivity()) {
                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable e) {
                        loadingDialog.dismiss();
                        ToastUtils.showShortToast(e.Message);
                        ll_wait_get_data.setVisibility(View.VISIBLE);
                        mRecyclerView.setVisibility(View.GONE);
                        refreshLayout.setVisibility(View.GONE);
                    }

                    @Override
                    public void onNext(List<OrderBetweenDto> myCarDataList) {
                        super.onNext(myCarDataList);
                        if (page == 1) {
                            if (myCarDataList.size() == 0) {
                                ll_wait_get_data.setVisibility(View.VISIBLE);
                                mRecyclerView.setVisibility(View.GONE);
                            } else {
                                ll_wait_get_data.setVisibility(View.GONE);
                                mRecyclerView.setVisibility(View.VISIBLE);
                            }
                        } else {
                            if (myCarDataList.size() == 0) {
                                ToastUtils.showShortToast("没有更多数据了...");
                            }
                        }
                        finishLoad();
                        list.addAll(myCarDataList);
                        loadingDialog.dismiss();
                        makeOrderAdapter.setList(list);
                    }
                });
    }

    private void finishLoad() {
        refreshLayout.finishLoadmore();
        refreshLayout.finishRefresh();
    }

    private void initListener() {
        refreshLayout.setOnRefreshListener(refreshlayout -> refresh());
        refreshLayout.setOnLoadmoreListener(refreshlayout -> load());

        makeOrderAdapter.setCancelButtonListener((type, orderId) -> {
            startActiviys(LogisticsActivity.class, orderId);
        });
        makeOrderAdapter.setSubmitButtonListener((type, orderId, shopId) -> {
            DialogUtils.dialog(getActivity(), "收货成功");
            DialogUtils.getTv_sure().setOnClickListener(view -> order(orderId));
        });
    }

    private void load() {
        page++;
        init(1);
        refreshLayout.finishLoadmore();
    }

    private void refresh() {
        page = 1;
        list = new ArrayList<>();
        init(2);
        refreshLayout.finishRefresh();
    }

    private void order(String orderId) {
        Map<String, String> map = new HashMap<>();
//        map.put("userId", userInfo.getUserId());
//        map.put("token", userInfo.getToken());
//        map.put("shopId", userInfo.getShopId());
        map.put("orderBetweenId", orderId);
        map.put("type", "3");
        loadingDialog.show();
        RetrofitClient.getInstance(getActivity())
                .createBaseApi()
                .sureOrder(map, new BaseSubscriber<ResponseBody>(getActivity()) {
                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable e) {
                        ToastUtils.showShortToast("网络错误");
                        loadingDialog.dismiss();

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        super.onNext(responseBody);
                        loadingDialog.dismiss();
                        try {
                            String request = responseBody.string();
                            JSONObject json = new JSONObject(request);
                            int status = json.getInt("code");
                            if (status == 0) {
                                DialogUtils.dismissDialog();
                                refresh();
                            } else {
                                DialogUtils.dismissDialog();
                                ToastUtils.showShortToast(json.getString("message"));
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
}
